package com.jumper.study.common.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.jumper.study.admin.bo.AdminUserDetails;
import com.jumper.study.admin.dto.resp.UserInfo;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.common.exception.Asserts;
import com.jumper.study.db.model.Account;

public class AdminUtil {
    @SuppressWarnings("null")
    public Long getAdminId() {
        AdminUserDetails detail = getDetails();
        if (detail == null) {
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }

        return detail.getAccount().getId();
    }

    public UserInfo getUserInfo() {
        AdminUserDetails detail = getDetails();
        UserInfo info = new UserInfo();
        info.setUsername(detail.getUsername())
            .setName(detail.getAccount().getName())
            .setAvatar(detail.getAccount().getAvatar());
        
        return info;
    }

    @SuppressWarnings("null")
    public Account getAccount() {
        AdminUserDetails detail = getDetails();
        if (detail == null) {
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        return detail.getAccount();
    }

    @SuppressWarnings("null")
    public AdminUserDetails getDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }

        return (AdminUserDetails)authentication.getPrincipal();
    }

    public boolean isLogged() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        Object principal = authentication.getPrincipal();
        return principal instanceof AdminUserDetails;
    }
}
